//
//  DBWMH.m
//  iphone.mobileoa
//
//  Created by 李林 on 13-10-24.
//  Copyright (c) 2013年 Epoint. All rights reserved.
//

#import "WMHDB.h"

@implementation WMHDB
///////////////////////////操作wmh_cache表///////////////////////////
//插入数据
+(void)insertWMHCache:(NSString *)keyValue withContent:(NSString *)content
{
    sqlite3 *database = [EpointFrameDB getFrameDB];
    
    if([content rangeOfString:@"'"].location!=NSNotFound){
        content=[content stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
    }
    char *errorMsg;
    NSString *msInsertSql = [NSString stringWithFormat:@"insert into wmh_cache values('%@','%@')",keyValue,content];
    
    NSString *delete = [NSString stringWithFormat:@"delete from wmh_cache where key = '%@' ",keyValue];
    sqlite3_exec(database,[delete UTF8String],NULL,NULL,&errorMsg);
    if (sqlite3_exec(database, [msInsertSql UTF8String], NULL, NULL, &errorMsg)==SQLITE_OK) {
//        NSLog(@"缓存成功!");
    }else{
        NSLog(@"缓存失败!");
    }
    [self dealErrorMessage:errorMsg];
}

//获取缓存值(根据key)
+(NSString *)getWMHCache:(NSString*)key
{
    sqlite3 *database = [EpointFrameDB getFrameDB];
    NSString *selectSql=[NSString stringWithFormat:@"select value from wmh_cache where key = '%@'",key];
    
    sqlite3_stmt *statement;
    NSString *nsvalue = @"";
    if (sqlite3_prepare_v2(database, [selectSql UTF8String], -1, &statement, nil)==SQLITE_OK) {
        NSLog(@"Query OK");
    }
    while (sqlite3_step(statement)==SQLITE_ROW) {
        char *value=(char *)sqlite3_column_text(statement, 0);
        nsvalue = [NSString stringWithUTF8String:value];
    }
    sqlite3_finalize(statement);
    return nsvalue;
}

//清空缓存
+(void)clearWMHCache{
    sqlite3 *database = [EpointFrameDB getFrameDB];
    char *errorMsg;
    NSString *sql = [NSString stringWithFormat:@"delete from wmh_cache"];
    if(sqlite3_exec(database,[sql UTF8String],NULL,NULL,&errorMsg)!=SQLITE_OK){
        NSLog(@"清空失败!");
        NSAssert1(NO,@"删除失败, %s", errorMsg);
    }else{
//        NSLog(@"清空成功!");
    }
    
}
+(void)dealErrorMessage:(char *)errorMsg
{
    if (errorMsg!=NULL) {
        NSLog(@"err:%s",errorMsg);
    }
}

@end
